/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.hycreate.platform.modules.crm.findcustomer;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hycreate.platform.common.config.Global;
import com.hycreate.platform.common.persistence.Page;
import com.hycreate.platform.common.utils.DateUtils;
import com.hycreate.platform.common.utils.IdGen;
import com.hycreate.platform.common.utils.StringUtils;
import com.hycreate.platform.common.utils.excel.ExportExcel;
import com.hycreate.platform.common.web.BaseController;
import com.hycreate.platform.modules.crm.business.CrmSysDict;
import com.hycreate.platform.modules.crm.business.SysDictService;
import com.hycreate.platform.modules.sys.entity.Area;
import com.hycreate.platform.modules.sys.service.AreaService;
import com.hycreate.platform.modules.sys.utils.UserUtils;

/**
 * 客户查询Controller
 * 
 * @author 方志钧
 * @version 2016-12-05
 */
@Controller
@RequestMapping(value = "${adminPath}/crm/findcustomer/findCustomer")
public class FindCustomerController extends BaseController {

	@Autowired
	private FindCustomerService findCustomerService;

	@Autowired
	private SysDictService dictService;

	@Autowired
	// 项目的service
	private FindCustomerProjectService projectService;

	@Autowired
	// 客户联系人的service
	private FindCustomerContactService contactService;

	@Autowired
	// 客户联系记录的service
	private FindCustomerRecordService recordService;

	@Autowired
	private AreaService areaService;

	@ModelAttribute
	public FindCustomer get(@RequestParam(required = false) String id) {
		FindCustomer entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = findCustomerService.get(id);
		}
		if (entity == null) {
			entity = new FindCustomer();
		}
		return entity;
	}

	@RequiresPermissions("findcustomer:findCustomer:view")
	@RequestMapping(value = { "list", "" })
	public String list(FindCustomer findCustomer, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Page<FindCustomer> page = findCustomerService.findPage(
				new Page<FindCustomer>(request, response), findCustomer);
		/*// 创建所有公司名的List
		List<String> customerNames = findCustomerService.findAllNames();*/

		// 查询所有省份
		List<Area> area = areaService.findAllProvince();

		// 创建所有行业名的List
		List<String> industryNames = dictService.findAllIndustryNames();

		model.addAttribute("industryNames", industryNames);
	/*	model.addAttribute("customerNames", customerNames);*/
		model.addAttribute("area", area);

		model.addAttribute("page", page);
		return "modules/crm/findcustomer/findCustomerList";
	}

	/**
	 * 搜索客户
	 * 
	 * @param findCustomer
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("findcustomer:findCustomer:view")
	@RequestMapping(value = { "searchCustomer" })
	public String searchCustomer(FindCustomer findCustomer,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Page<FindCustomer> page = findCustomerService.findCustomerPage(
				new Page<FindCustomer>(request, response), findCustomer);

		/*// 创建所有公司名的List
		List<String> customerNames = findCustomerService.findAllNames();*/

		// 创建所有行业名的List
		List<String> industryNames = dictService.findAllIndustryNames();

		// 查询所有省份
		List<Area> area = areaService.findAllProvince();
		model.addAttribute("area", area);

		model.addAttribute("industryNames", industryNames);
		/*model.addAttribute("customerNames", customerNames);*/

		model.addAttribute("page", page);
		return "modules/crm/findcustomer/findCustomerList";
	}

	/**
	 * 我的收藏
	 */
	@RequestMapping(value = { "myCollect" })
	public String myCollect(FindCustomer findCustomer,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Page<FindCustomer> page = findCustomerService.findMyCollectCustomer(
				new Page<FindCustomer>(request, response), findCustomer,
				UserUtils.getUser().getId());
		model.addAttribute("page", page);
		return "modules/crm/findcustomer/myCollect";
	}

	/**
	 * 取消收藏
	 */
	@RequestMapping(value = { "cacleCollect" })
	public String cacleCollect(String customerId, HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String userId = UserUtils.getUser().getId();

		try {
			findCustomerService.cacleCollect(userId, customerId);
			addMessage(redirectAttributes, "释放成功");
			return "redirect:" + Global.getAdminPath()
					+ "/crm/findcustomer/findCustomer/myCollect";
		} catch (Exception e) {
			addMessage(redirectAttributes, "系统内部错误，删除失败");
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 查看客户详情
	 */
	@RequiresPermissions("findcustomer:findCustomer:view")
	@RequestMapping(value = "form")
	public String form(FindCustomer findCustomer, HttpServletRequest request,
			HttpServletResponse response, Model model) {

		// 找到该客户的收藏者ID
		String collecterId = findCustomerService
				.getCustomerCollecterId(findCustomer.getId());

		// 根据客户查询所有联系人
		List<FindCustomerContact> contacts = contactService
				.findContactsByCustomer(findCustomer.getId());
		// 根据客户查询所有项目
		List<FindCustomerProject> projects = projectService
				.findProjectsByCustomer(findCustomer.getId());
		// 根据客户查询所有行业
		List<CrmSysDict> industrys = dictService
				.findIndustryNameByCustomer(findCustomer.getId());

		List<CrmSysDict> allIndustrys = dictService.finAllIndustry();

		// 将customerId封装在FindCustomerRecord对象中
		FindCustomerRecord record = new FindCustomerRecord();
		record.setCustomerId(findCustomer.getId());

		// 获得最近10条联系记录
		List<FindCustomerRecord> records = recordService
				.findTenRecordsByCustomer(findCustomer.getId());

		// 将以上数据传到前台
		model.addAttribute("collecterId", collecterId);
		model.addAttribute("allIndustrys", allIndustrys);
		model.addAttribute("industrys", industrys);
		model.addAttribute("record", record);
		model.addAttribute("records", records);
		model.addAttribute("projects", projects);
		model.addAttribute("contacts", contacts);
		model.addAttribute("findCustomer", findCustomer);
		return "modules/crm/findcustomer/findCustomerForm";
	}

	/**
	 * 添加联系记录
	 */
	@RequiresPermissions("findcustomer:findCustomer:view")
	@RequestMapping(value = "addRecord")
	public String addRecord(FindCustomerRecord record,
			HttpServletRequest request, HttpServletResponse response,
			Model model, RedirectAttributes redirectAttributes) {
		FindCustomer customer = new FindCustomer();
		customer.setId(record.getCustomerId());
		if(!record.getIsNewRecord()){
			recordService.save(record);
		}else{
			record.setId(IdGen.uuid());
			record.setCreateBy(UserUtils.getUser());
			record.setUpdateBy(UserUtils.getUser());
			recordService.addRecordForCustomer(record);
			
			findCustomerService.updateLastContant(record.getCustomerId()); //修改公司的最近联系时间
		}
		
		addMessage(redirectAttributes, "联系记录添加成功");
		return "redirect:" + Global.getAdminPath()
				+ "/crm/findcustomer/findCustomer/form?id=" + customer.getId();
	}

	/**
	 * 修改客户地址
	 * 
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "updateAddress")
	public String updateAddress(FindCustomer findCustomer,
			HttpServletRequest request, HttpServletResponse response,
			Model model, RedirectAttributes redirectAttributes) {
		findCustomerService.save(findCustomer);
		addMessage(redirectAttributes, "地址修改成功");
		return "redirect:" + Global.getAdminPath()
				+ "/crm/findcustomer/findCustomer/form?id="
				+ findCustomer.getId();
	}

	/**
	 * 删除客户行业
	 */
	@RequestMapping(value = "deleteIndustry")
	public String deleteIndustry(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		String customerId = request.getParameter("customerId");
		String industryId = request.getParameter("industryId");

		findCustomerService.deleteIndustry(customerId, industryId);
		addMessage(redirectAttributes, "行业删除成功");
		return "redirect:" + Global.getAdminPath()
				+ "/crm/findcustomer/findCustomer/form?id=" + customerId;
	}

	/**
	 * 添加客户行业
	 */
	@RequestMapping(value = "addIndustry")
	public String addIndustry(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {
		String customerId = request.getParameter("customerId");
		String industryId = request.getParameter("industryId");
		findCustomerService.addIndustryForCustomer(IdGen.uuid(), customerId,
				industryId);
		addMessage(redirectAttributes, "行业添加成功");
		return "redirect:" + Global.getAdminPath()
				+ "/crm/findcustomer/findCustomer/form?id=" + customerId;
	}

	/**
	 * 验证客户是否已经有该行业
	 * 
	 * @throws IOException
	 */
	@RequestMapping(value = "isExist")
	public void isExist(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) throws IOException {
		String customerId = request.getParameter("customerId");
		String industryId = request.getParameter("industryId");
		int result = findCustomerService.isExist(customerId, industryId);
		response.setContentType("application/text");
		if (result > 0) {
			response.getWriter().print("true");
		} else {
			response.getWriter().print("false");
		}
	}

	@RequiresPermissions("findcustomer:findCustomer:edit")
	@RequestMapping(value = "save")
	public String save(FindCustomer findCustomer, Model model,
			RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, findCustomer)) {
			return form(findCustomer, null, null, model);
		}
		findCustomerService.save(findCustomer);
		addMessage(redirectAttributes, "保存客户查询成功");
		return "redirect:" + Global.getAdminPath()
				+ "/crm/findcustomer/findCustomer/?repage";
	}

	@RequiresPermissions("findcustomer:findCustomer:deleteCustomer")
	@RequestMapping(value = "delete")
	public String delete(FindCustomer findCustomer,
			RedirectAttributes redirectAttributes) {
		List<FindCustomerProject> projects = projectService
				.findProjectsByCustomer(findCustomer.getId());
		List<FindCustomerContact> contacts = contactService
				.findContactsByCustomer(findCustomer.getId());
		if (projects.size() > 0) {
			addMessage(redirectAttributes, "删除客户失败！该客户下有项目");
			return "redirect:" + Global.getAdminPath()
					+ "/crm/findcustomer/findCustomer/?repage";
		} else if (contacts.size() > 0) {
			addMessage(redirectAttributes, "删除客户失败！该客户下有联系人");
			return "redirect:" + Global.getAdminPath()
					+ "/crm/findcustomer/findCustomer/?repage";
		} else {
			findCustomerService.delete(findCustomer);
			addMessage(redirectAttributes, "删除客户成功");
			return "redirect:" + Global.getAdminPath()
					+ "/crm/findcustomer/findCustomer/?repage";
		}
	}

	@RequestMapping(value = { "toUpdateBase" })
	public String toUpdateBase(String customerId, HttpServletRequest request,
			HttpServletResponse response, Model model) {

		// 查询所有省份
		List<Area> area = areaService.findAllProvince();
		model.addAttribute("area", area);

		FindCustomer customer = new FindCustomer();
		customer.setId(customerId);
		customer = findCustomerService.get(customer);
		model.addAttribute("customer", customer);
		return "modules/crm/findcustomer/updateCustomerBase";
	}

	/**
	 * 修改基本信息
	 */
	@RequestMapping(value = { "updateBase" })
	public String updateBase(FindCustomer customer, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		findCustomerService.save(customer);
		return "redirect:" + Global.getAdminPath()
				+ "/crm/findcustomer/findCustomer/form?id=" + customer.getId();
	}

	/**
	 * 加入我的客户
	 */
	@RequestMapping(value = { "addMyCustomer" })
	public String addMyCustomer(@RequestParam("customerId") String customerId,
			HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		String userId = UserUtils.getUser().getId();

		String collecterId = findCustomerService.alreadyCollect(customerId);
		if (null != collecterId) {
			addMessage(redirectAttributes, "添加失败，该客户已被其他用户收藏");
			return "redirect:" + Global.getAdminPath()
					+ "/crm/findcustomer/findCustomer/form?id=" + customerId;
		}

		findCustomerService.addMyCustomer(userId, customerId);
		addMessage(redirectAttributes, "添加成功");
		return "redirect:" + Global.getAdminPath()
				+ "/crm/findcustomer/findCustomer/form?id=" + customerId;
	}
	
	

	/**
	 * 删除用户的联系记录
	 * @author zzf
	 * 2016年12月28日 11:19:47
	 */
	@RequestMapping(value = { "delCustomerContant" })
	public String delCustomerContant(@Param("contactid") String contactid,@Param("customerid")String customerid,Model model){
		
	
		findCustomerService.delCustomerContant(contactid);
	
	
		
		return "redirect:" + Global.getAdminPath()
				+ "/crm/findcustomer/findCustomer/form?id=" + customerid;
	}
	

	/**
	 * 客户数据导出
	 */
	@RequestMapping(value = { "exportAll" })
	public String exportAll(FindCustomer customer, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes) {
		String customerIds = request.getParameter("customerIds");
		customerIds = customerIds.trim();
		customerIds = replaceBlank(customerIds);
		if (customerIds == null || customerIds.length() <= 0) {
			addMessage(redirectAttributes, "没有客户需要导出");
			return "redirect:" + Global.getAdminPath()
					+ "/crm/findcustomer/findCustomer/list";
		}
		customerIds = customerIds.substring(0, customerIds.length() - 1);
		String[] custId = customerIds.split(",");
		try {
			String fileName = "CustomerData"
					+ DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			// 查询数据
			/*
			 * List<FindCustomer>
			 * customers=findCustomerService.findList(customer);
			 */
			List<ExcelCustomerMould> customers = findCustomerService
					.findListByIds(custId);
			// 1：创建Excel导出对象；2：设置数据；3：写入输出流；4：临时数据销毁
			new ExportExcel("客户数数据", ExcelCustomerMould.class)
					.setDataList(customers).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出用户失败！失败信息：" + e.getMessage());
			e.printStackTrace();
		}
		return "redirect:" + Global.getAdminPath()
				+ "/crm/findcustomer/findCustomer/list";
	}

	/**
	 * 去字符串中间的空格和换行符、制表符等
	 */
	public String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

}